import 'package:fishing/models/booking_args.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../models/fishing_spot.dart';
import '../../models/pond.dart';
import '../../models/facility.dart';
import '../../services/home_service.dart';
// import '../../services/location_service.dart';

class FishingDetailPage extends StatefulWidget {
  final String id;
  const FishingDetailPage({super.key, required this.id});

  @override
  State<FishingDetailPage> createState() => _FishingDetailPageState();
}

class _FishingDetailPageState extends State<FishingDetailPage> {
  final HomeService _homeService = HomeService();
  // final LocationService _locationService = LocationService();

  FishingSpot? _fishingSpot;
  List<Pond> _ponds = [];
  bool _isLoading = true;
  bool _isLoadingPonds = true;
  double? _userLatitude;
  double? _userLongitude;

  @override
  void initState() {
    super.initState();
    _loadFishingSpotDetail();
  }

  Future<void> _loadFishingSpotDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _isLoadingPonds = true;
      });

      // 获取用户位置
      if (_userLatitude == null || _userLongitude == null) {
        // 真实位置获取
        // final locationInfo = await _locationService.getCurrentLocationInfo();
        // if (locationInfo['success'] == true) {
        //   _userLatitude = locationInfo['latitude'];
        //   _userLongitude = locationInfo['longitude'];
        // }
        _userLatitude = 23.1291;
        _userLongitude = 113.2644;
      }

      final result = await _homeService.getFishingSpotDetailWithPonds(
        widget.id,
        userLatitude: _userLatitude,
        userLongitude: _userLongitude,
      );

      if (mounted) {
        if (result != null) {
          setState(() {
            _fishingSpot = result['fishingSpot'] as FishingSpot;
            _ponds = result['ponds'] as List<Pond>;
            _isLoading = false;
            _isLoadingPonds = false;
          });
        } else {
          setState(() {
            _isLoading = false;
            _isLoadingPonds = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isLoadingPonds = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.white,
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _fishingSpot == null
              ? _buildErrorWidget()
              : _buildContent(),
    );
  }

  Widget _buildErrorWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '钓场信息加载失败',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadFishingSpotDetail,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return CustomScrollView(
      slivers: [
        _buildSliverAppBar(),
        SliverToBoxAdapter(
          child: Column(
            children: [
              _buildFishingSpotInfo(),
              _buildPondSection(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 300,
      pinned: true,
      backgroundColor: Colors.blue[600],
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.white),
        onPressed: () => context.pop(),
      ),
      flexibleSpace: FlexibleSpaceBar(
        title: Text(
          _fishingSpot?.name ?? '',
          style: const TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
        background: _buildHeaderImage(),
      ),
    );
  }

  Widget _buildHeaderImage() {
    if (_fishingSpot?.images.isEmpty ?? true) {
      return Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue[400]!,
              Colors.blue[600]!,
            ],
          ),
        ),
        child: const Center(
          child: Icon(
            Icons.image_not_supported,
            size: 80,
            color: Colors.white54,
          ),
        ),
      );
    }

    return Stack(
      fit: StackFit.expand,
      children: [
        Image.network(
          _fishingSpot!.images[0],
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.blue[400]!,
                    Colors.blue[600]!,
                  ],
                ),
              ),
              child: const Center(
                child: Icon(
                  Icons.image_not_supported,
                  size: 80,
                  color: Colors.white54,
                ),
              ),
            );
          },
        ),
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.transparent,
                Colors.black.withOpacity(0.7),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildFishingSpotInfo() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 基本信息
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _fishingSpot!.name,
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Icon(Icons.location_on,
                            size: 16, color: Colors.grey[600]),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Text(
                            _fishingSpot!.address,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color:
                      _fishingSpot!.isOpen ? Colors.green[50] : Colors.red[50],
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  _fishingSpot!.isOpen ? '营业中' : '已关闭',
                  style: TextStyle(
                    fontSize: 14,
                    color: _fishingSpot!.isOpen
                        ? Colors.green[600]
                        : Colors.red[600],
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),

          const SizedBox(height: 16),

          // 评分和价格
          Row(
            children: [
              if (_fishingSpot!.reviewCount > 0) ...[
                Icon(Icons.star, size: 20, color: Colors.amber[600]),
                const SizedBox(width: 4),
                Text(
                  _fishingSpot!.rating.toStringAsFixed(1),
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.amber[800],
                  ),
                ),
                Text(
                  ' (${_fishingSpot!.reviewCount}条评价)',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                const Spacer(),
              ] else
                const Spacer(),
              Text(
                _fishingSpot!.priceRange,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.blue[600],
                ),
              ),
            ],
          ),

          const SizedBox(height: 16),

          // 营业时间
          _buildInfoRow(Icons.access_time, '营业时间', _fishingSpot!.openHours),

          const SizedBox(height: 12),

          // 联系电话
          if (_fishingSpot!.phone.isNotEmpty)
            _buildInfoRow(Icons.phone, '联系电话', _fishingSpot!.phone),

          const SizedBox(height: 16),

          // 鱼类
          if (_fishingSpot!.fishTypes.isNotEmpty) ...[
            const Text(
              '鱼类',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _fishingSpot!.fishTypes.map((fish) {
                return Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    fish,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.blue[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 16),
          ],

          // 设施
          _buildFacilities(),

          const SizedBox(height: 16),

          // 描述
          if (_fishingSpot!.description.isNotEmpty) ...[
            const Text(
              '钓场介绍',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _fishingSpot!.description,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[700],
                height: 1.5,
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(
      children: [
        Icon(icon, size: 18, color: Colors.grey[600]),
        const SizedBox(width: 8),
        Text(
          '$label: ',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
          ),
        ),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(
              fontSize: 14,
              color: Colors.black87,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildFacilities() {
    if (_fishingSpot == null) {
      return const SizedBox.shrink();
    }

    // 获取所有设施数据
    final allFacilities = Facility.getMockFacilities();
    
    // 根据设施ID获取对应的设施信息，显示全部设施
    final spotFacilities = _fishingSpot!.facilityIds
        .map((id) => allFacilities.firstWhere(
              (facility) => facility.id == id,
              orElse: () => Facility(id: 0, name: '未知设施', description: ''),
            ))
        .where((facility) => facility.id != 0) // 过滤掉未知设施
        .toList();

    if (spotFacilities.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '设施服务',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 8),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[200]!),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.grey[500], size: 20),
                const SizedBox(width: 8),
                Text(
                  '暂无设施信息',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text(
              '设施服务',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.blue[50],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '${spotFacilities.length}项',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.blue[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: spotFacilities.map((facility) {
            return _buildCompactFacilityChip(facility);
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildCompactFacilityChip(Facility facility) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: Facility.getColorForFacility(facility.name).withOpacity(0.1),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: Facility.getColorForFacility(facility.name).withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Facility.getIconForFacility(facility.name),
            size: 16,
            color: Facility.getColorForFacility(facility.name),
          ),
          const SizedBox(width: 6),
          Text(
            facility.name,
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w500,
              color: Facility.getColorForFacility(facility.name),
            ),
          ),
        ],
      ),
    );
  }
 
  Widget _buildPondSection() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                '鱼塘列表',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
              const Spacer(),
              if (_isLoadingPonds)
                const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                ),
            ],
          ),
          const SizedBox(height: 16),
          _isLoadingPonds
              ? const Center(
                  child: Padding(
                    padding: EdgeInsets.all(32),
                    child: CircularProgressIndicator(),
                  ),
                )
              : _ponds.isEmpty
                  ? _buildEmptyPondList()
                  : _buildPondList(),
        ],
      ),
    );
  }

  Widget _buildEmptyPondList() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          children: [
            Icon(
              Icons.water_drop_outlined,
              size: 60,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              '暂无鱼塘信息',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPondList() {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: _ponds.length,
      separatorBuilder: (context, index) => const SizedBox(height: 12),
      itemBuilder: (context, index) {
        return _buildPondCard(_ponds[index], index);
      },
    );
  }

  Widget _buildPondCard(Pond pond, index) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 鱼塘名称和标签
          Row(
            children: [
              Expanded(
                child: Text(
                  pond.name,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              if (pond.canReturnFish)
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.orange[50],
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    '可回鱼',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.orange[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              if (!pond.canReturnFish)
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    '纯玩',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.blue[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
            ],
          ),

          const SizedBox(height: 12),

          // 鱼塘信息
          Row(
            children: [
              // Expanded(
              //   child: _buildPondInfo('当前存鱼', '${pond.currentWeight.toInt()}斤'),
              // ),
              Expanded(
                child: _buildPondInfo('存鱼量', '${pond.actualWeight.toInt()}斤'),
              ),
            ],
          ),

          // if (pond.remark?.isNotEmpty ?? false) ...[
          //   const SizedBox(height: 8),
          //   Text(
          //     '备注: ${pond.remark}',
          //     style: TextStyle(
          //       fontSize: 14,
          //       color: Colors.grey[600],
          //       fontStyle: FontStyle.italic,
          //     ),
          //   ),
          // ],

          const SizedBox(height: 12),

          // 价格段
          if (pond.priceSegments.isNotEmpty) ...[
            const Text(
              '价格方案',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 8),
            ...pond.priceSegments
                .map((segment) => _buildPriceSegment(segment, index)),
          ],
        ],
      ),
    );
  }

  Widget _buildPondInfo(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
        const SizedBox(height: 2),
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }

  Widget _buildPriceSegment(PriceSegment segment, index) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '¥${segment.price.toInt()}',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue[600],
                  ),
                ),
                Text(
                  '${segment.durationHours}小时',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          if (segment.returnPrice != null)
            Text(
              '回鱼¥${segment.returnPrice!.toInt()}/斤',
              style: TextStyle(
                fontSize: 14,
                color: Colors.orange[600],
                fontWeight: FontWeight.w500,
              ),
            ),
          const SizedBox(width: 12),
          ElevatedButton(
            onPressed: () => _bookPond(segment, index),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue[600],
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            ),
            child: const Text('预订'),
          ),
        ],
      ),
    );
  }

  void _bookPond(PriceSegment segment, index) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('预订确认'),
        content: Text(
            '确定要预订这个价格方案吗？\n价格: ¥${segment.price.toInt()}\n时长: ${segment.durationHours}小时'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // 关闭弹窗
              Navigator.of(context).pop();
              // 跳转页面
              context.push(
                '/fishing/${widget.id}/book/${segment.pondId}',
                extra: BookingArgs(
                  deptId: widget.id,
                  priceSegmentId:'${segment.id}',
                  pondId: segment.pondId,
                  pondName: _ponds[index].name,
                  price: segment.price,
                  durationHours: segment.durationHours,
                  openHours: _fishingSpot!.openHours,
                ),
              );
            },
            child: const Text('确认预订'),
          ),
        ],
      ),
    );
  }
}
